const querystring = require('querystring')
const handleBlogRouter = require('./src/router/blog')


const getPostData = (req) => {
  const promise = new Promise((resovle, reject) => {
    if (req.method !== 'POST') {
      resovle({});
      return;
    }
    if (req.headers['content-type'] !== 'application/json') {
      resovle({});
      return;
    }
    let resData = '';
    req.on('data', chunk => {
      resData += chunk.toString();
    })
    req.on('end', () => {
      if (!resData) {
        resovle({})
        return;
      }
      resovle(
        JSON.parse(resData)
      )
    })
  })
  return promise
}

const serverHandle = (req, res) => {
  res.setHeader('Content-Type', 'application/json');
  const url = req.url
  req.path = url.split('?')[0]
  req.query = querystring.parse(url.split('?')[1])

  getPostData(req).then(async resData => {
    req.body = resData;
    const routeData = await handleBlogRouter(req, res);
    if (routeData) {
      res.end(
        JSON.stringify(routeData)
      )
      return;
    }
    res.writeHead(400, { 'Content-Type': 'text/plain' })
    res.write('404 Not Found')
    res.end()
  })
}

module.exports = serverHandle